package com.jy.datapipeline.export.quartz;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.jy.datapipeline.common.util.BeanFactoryUtil;
import com.jy.datapipeline.export.entity.DataStoreInfoModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteDetailLogModel;
import com.jy.datapipeline.export.properties.QuartzProperties;
import com.jy.datapipeline.export.service.DataStoreInfoService;
import com.jy.datapipeline.export.service.ExpTaskExecuteDetailLogService;
import com.jy.datapipeline.export.service.ExpTaskExecuteLogService;
import com.jy.datapipeline.export.service.ExpTaskService;
import com.jy.datapipeline.common.util.FtpUtil;
import com.jy.datapipeline.common.util.TEAUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
//@Component
public class JobDetailCheckFeedBackHandler extends QuartzJobBean {
//    @Value("${config.checkdelayhour}")
//    public   int checkdelayhour;
//    @Autowired
//    private  ExpTaskService expTaskService;
//    @Autowired
//    private  ExpTaskExecuteLogService expTaskExecuteLogService;
//    @Autowired
//    private  ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService;
//    @Autowired
//    private  DataStoreInfoService dataStoreInfoService;
//    public JobDetailCheckFeedBackHandler(ExpTaskService expTaskService,
//        ExpTaskExecuteLogService expTaskExecuteLogService,
//        ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService,
//        DataStoreInfoService dataStoreInfoService) {
//        this.expTaskService = expTaskService;
//        this.expTaskExecuteLogService = expTaskExecuteLogService;
//        this.expTaskExecuteDetailLogService = expTaskExecuteDetailLogService;
//        this.dataStoreInfoService = dataStoreInfoService;
//    }


    @Override
    protected void executeInternal(JobExecutionContext context)  {
        ExpTaskService expTaskService = BeanFactoryUtil.getBean(ExpTaskService.class);
        ExpTaskExecuteLogService expTaskExecuteLogService = BeanFactoryUtil.getBean(ExpTaskExecuteLogService.class);
        ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService = BeanFactoryUtil.getBean(ExpTaskExecuteDetailLogService.class);
        DataStoreInfoService dataStoreInfoService = BeanFactoryUtil.getBean(DataStoreInfoService.class);
        QuartzProperties quartzProperties = BeanFactoryUtil.getBean(QuartzProperties.class);

        AtomicReference<ChannelSftp> channelSftp=new AtomicReference<>();
        AtomicReference<List<String>> fileList=new AtomicReference<>();
        try{
            //查询上传完成的文件

            List<ExpTaskExecuteDetailLogModel> etedlmList= expTaskExecuteDetailLogService.findByExpStatus(4,quartzProperties.getCheckdelayhour());//sftp上传完成
            if(etedlmList.size()>0){
                DataStoreInfoModel dsim= dataStoreInfoService.findByStoreId(etedlmList.get(0).getStoreId());

                log.info("checkFeedback start file length: {} ",etedlmList.size());
                if(channelSftp.get()==null){
                    channelSftp.set(FtpUtil.connectBySftp(dsim.getHost(), dsim.getUserName(),TEAUtil.decode(dsim.getPassword())));
                }

                etedlmList.forEach( etedl->{
                    //检查是否有反馈文件

                    // String OkFilepath=dsim.getRemotePath()+"/"+etedl.getDataFileNamePrefix()+".ok";
                    //log.info("开始清除文件==>"+OkFilepath);
                    String verifyFilepath=dsim.getRemotePath()+"/"+etedl.getDataFileNamePrefix()+".verf";
                    try {

//                        if(fileList.get()==null){
//                            fileList.set(
//                                FtpUtil.getSftpFileList(dsim.getRemotePath(), channelSftp.get()));
//                        }
                        String OkResult="";
                        String verifyResult="";
                        // if(fileList!=null && fileList.get().size()>0){
                        //  for (String file: fileList.get()){
                        String okfileName=etedl.getDataFileNamePrefix()+".ok";
                        String verifyName=etedl.getDataFileNamePrefix()+".verf";
//                                if(file.equals(okfileName)){
                        OkResult=FtpUtil.readFileBySftp(channelSftp.get(),dsim.getRemotePath(),okfileName);
                        // fileList.get().remove(file);
//                                }
//                                if(file.equals(verifyName)){
                        verifyResult=FtpUtil.readFileBySftp(channelSftp.get(),dsim.getRemotePath(),verifyName);
                        // fileList.get().remove(file);
//                                }
//                            }
//                        }
                        if (OkResult != null && !OkResult.equals("")) {
                            log.info("check feedback verifyResult {} OkResult {} ",verifyFilepath,OkResult);
                            if(OkResult.equals(verifyResult)){
                                //反馈成功
                                etedl.setExpStatus(5);//反馈成功
                                etedl.setFeedbackTime(new Date());
                                expTaskExecuteDetailLogService.updateExpStatus(etedl);
                                String dataFilePathPreff=etedl.getDataFilePath().split("\\.")[0];
                                //删除本地文件
                                File datefile=new File(etedl.getDataFilePath());
                                File verifyfile=new File(dataFilePathPreff+".verf");
                                if(datefile.isFile() && verifyfile.isFile()){
                                    datefile.delete();
                                    verifyfile.delete();
                                }
                                //远程删除
                                String sftpDateFilePath=etedl.getDataFileNamePrefix()+".dat";
                                String sftpVerifyFilePath=etedl.getDataFileNamePrefix()+".verf";
                                String sftpOkFilePath=etedl.getDataFileNamePrefix()+".ok";
                                FtpUtil.deleteFile(channelSftp.get(),dsim.getRemotePath(),sftpDateFilePath);
                                FtpUtil.deleteFile(channelSftp.get(),dsim.getRemotePath(),sftpVerifyFilePath);
                                FtpUtil.deleteFile(channelSftp.get(),dsim.getRemotePath(),sftpOkFilePath);
                                ;
                                etedl.setExpStatus(7);//反馈成功
                                etedl.setDeleteTime(new Date());
                                expTaskExecuteDetailLogService.updateExpStatus(etedl);

                                expTaskExecuteLogService.updateExeuceStatus(etedl.getTaskExecutelogLogId(),2,0,"","");

                                expTaskService.updateExpTaskStatus(2,etedl.getTaskId(),"");
                            }

                        }


                    } catch (JSchException | SftpException e) {
                        log.info(verifyFilepath);

                        //this.expTaskExecuteLogService.updateExeuceStatus(etedl.getTaskExecutelogLogId(),-1);
                        log.error("SftpException  ",e);
                    }

                });


            }
        }
        catch (Exception e){
            log.error("Exception ",e);
        }finally {
            if (  channelSftp.get()!=null){
                FtpUtil.disconnect(channelSftp.get());

            }
        }

    }
}
